var express = require('express');
var router = express.Router();
var sql = require('./../tool/sql');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var md5 = require('md5');
var fs = require('fs');
var UserModel = require('../tool/model/user.js');
var clientModel = require('../tool/model/clientUser.js');
/* GET home page. */
router.get('/',  function(req, res, next) {
  if (req.cookies.isLogin === 'ok') {
    res.render('index', {
      roots: req.cookies.root,
      userName:req.cookies.userName
    });
  } else {
    res.redirect('/login')
  }
  // res.render('login');
  
});
router.get('/login', function(req, res, next) {
  res.render('login');
});
router.get('/logout', function(req, res, next) {
  // 删除cookie
  res.clearCookie('isLogin')
  // 修改cookie的值
  // res.cookie('isLogin', 'aa')
  res.redirect('/login')
});

router.post('/loginAction', async function (req, res, next) {
  let obj = req.body; // {userName: '', userPassword:''}
  obj.userPassword = md5(obj.userPassword)
  console.log(obj)
  
  await UserModel.find(obj,function(err,docs){
    if(err){
      console.log(err);
      return;
  }
    if (docs.length === 0) {
      let userEmail = obj.userName
      let userPassword = obj.userPassword
      clientModel.find({$or:[{'userEmail': userEmail, 'userPassword':userPassword}]},function(errs,doc){
        if(errs){
          console.log(err);
          return;
      }
      if (doc.length === 0) {
          console.log('clientusr')
          res.send('/error')
        } else {
          res.cookie('id',doc[0].userID,{maxAge: 1000*60*60*5,singed:true, httpOnly: true})
          res.cookie('username',doc[0].userName,{maxAge: 3600,singed:true, httpOnly: true})
          res.cookie('isLogin', 'ok')
          res.cookie('root',doc[0].userRoots)
          res.redirect('/')
        }
      })
    }else{
      console.log('usrs')
      res.cookie('id',docs[0].userID,{maxAge: 3600000*24,singed:true, httpOnly: true})
      res.cookie('isLogin', 'ok')
      res.cookie('root',docs[0].userRoots)
      res.redirect('/')
    }
     
  })
  
});
router.post('/add',async function(req, res, next) {
  let obj = req.body;
  obj.password = md5(obj.password)
  var user = new UserModel ({
      userName:obj.username,
      userPassword:obj.password,
      userEmail:obj.email,//以邮箱作为该用户的管理标识，若更该则更新此字段
      userPhone:obj.phone
    })
    await user.save(function(err){
      if(err){
          console.log(err);
          return;
      }else{
        res.redirect('/login')
      }
  })
});

module.exports = router;
